package sql;
import java.io.*;
import java.sql.*;
import java.util.Properties;

public class DataAccess 
{
	private Connection conn = null;
	private String jdbcUrl;
	private String username;
	private String password;
	
	public DataAccess() {
		Properties prop = new Properties();

	    try {
	    	InputStream in = getClass().getResourceAsStream("/database.properties");
	        prop.load(in);
            jdbcUrl = prop.getProperty("jdbcUrl");
	        username = prop.getProperty("username");
	        password = prop.getProperty("password");
        
	    } catch (IOException ex) {
	        ex.printStackTrace();
	    }
	}
	
	private static void checkDriver() throws ClassNotFoundException {			
		Class.forName("com.mysql.jdbc.Driver");		
	}
	
	public Connection getConnection() throws ClassNotFoundException, SQLException  {
		checkDriver();
		
		// create connection if there is no connection
		if (conn == null) {
			conn = DriverManager.getConnection(jdbcUrl, username, password);			
		}
		
		return conn;
	}
	
	// returns result set for the select query
	public ResultSet getSelectResult(String query) throws ClassNotFoundException, SQLException {
		getConnection();
		Statement stmt;
		
		stmt = conn.createStatement();
		ResultSet rset = stmt.executeQuery(query);
		return rset;
	}
	
	public int executeUpdate(String query) throws ClassNotFoundException, SQLException {
		getConnection();
		Statement stmt;
		
		stmt = conn.createStatement();
		int status = stmt.executeUpdate(query);
		return status;		
	}

	public ResultSet getSelectResult(PreparedStatement preparedStatement) throws ClassNotFoundException, SQLException {
		ResultSet rset = preparedStatement.executeQuery();
		return rset;
	}
	
	public int executeUpdate(PreparedStatement preparedStatement) throws ClassNotFoundException, SQLException {
		int status = preparedStatement.executeUpdate();
		return status;				
	}
	
	public void closeConnection() throws SQLException {
		conn.close();
	}
}
